package com.zyk.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhangsan
 * @date 2021/6/13 21:15
 */
public class C51 {

    boolean[][] used;
    List<List<String>> ans = new ArrayList<>();
    LinkedList<String> list = new LinkedList<>();

    // n*n 的棋盘, 返回所有可摆放的方法
    public List<List<String>> solveNQueens(int n) {
        used = new boolean[n][n];
        process(0, n);
        return ans;
    }

    public void process(int i, int N) {
        if(i == N) {
            ans.add(new ArrayList<>(list));
        }
        char[] str = new char[N];
        Arrays.fill(str, '.');
        for (int c = 0; c < N; c++) {
            boolean can = true;
            for (int k = 0; k < i; k++) {
                int distance = i - k;
                // 如果上边, 或者左上直线, 或者右上直线
                if(used[k][c] || ((c-distance) >= 0 && used[k][c-distance]) || ((c + distance) < N && used[k][c+distance])) {
                    can = false;
                    break;
                }
            }

            if(can) {
                used[i][c] = true;
                str[c] = 'Q';
                list.addLast(new String(str));

                process(i+1, N);

                str[c] = '.';
                used[i][c] = false;
                list.removeLast();
            }
        }
    }


    // for test
    public static void main(String[] args) {
        int n = 4;
        List<List<String>> ans = new C51().solveNQueens(n);
        for (List<String> an : ans) {
            for (String s : an) {
                System.out.println(s);
            }
        }
    }

}
